var beiMiCommon = require("BeiMiCommon");
//var sanm = null;
var SG_APPID = "Y0xt47hqlHzgHDHj";
var SG_APPSECRET = "RKS7mvr9uHHH9wdb";

cc.Class({
    extends: beiMiCommon,

    // use this for initialization
    onLoad: function () {
        if(cc.sys.os == cc.sys.OS_WINDOWS){
            var newUrl = window.location.search;
            var code = null;
            if(newUrl){
              code = newUrl.split("code=")[1];
              if(code){
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                        var data = xhr.responseText;
                        console.log(data);
                        var res = JSON.parse(data);
                        var openid = res.openid;
                        var access_token = res.access_token;
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                                var response = xhr.responseText;
                                console.log(response);
                            }
                        };
                        xhr.open("GET", "https://demo.shuxing.net.cn/api/wx/auth?code="+code, true);
                        xhr.send();
                    }
                };
                xhr.open("GET", "https://demo.shuxing.net.cn/api/wx/auth?code="+code, true);
                xhr.send();
              }
            }
        }
        var node = cc.find("Canvas");
        this.sanm = node.getChildByName("global").getChildByName("main").getChildByName("agree").getComponent(cc.Label);
        node.getChildByName("global").getChildByName("main").getChildByName("test").active = false;
        node.getChildByName("global").getChildByName("main").getChildByName("submit").active = false;
        node.getChildByName("global").getChildByName("button").getChildByName("test1").active = true;
        node.getChildByName("global").getChildByName("button").getChildByName("test2").active = true;
    },
    editIp:function(){
        var node = cc.find("Canvas");
        var ip = node.getChildByName("global").getChildByName("main").getChildByName("test").getComponent(cc.EditBox).string;
        console.log(ip)
        cc.sys.localStorage.setItem("myIp", ip);
    },
    logout:function(){
        //cc.director.end();
        console.log(cc.sys.localStorage.getItem("myIp"))
        console.log("退出")
        if(cc.sys.os == cc.sys.OS_ANDROID){
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "exitApp","()V");
        }
    },
    login:function(){
        this.io = require("IOUtils");//获取本地存储
        //console.log(this.io)
        this.loadding();
        if(this.io.get("userinfo") == null){
            //发送游客注册请求
            var xhr = cc.beimi.http.httpGet("/api/guest", this.sucess , this.error , this);
        }else{
            //通过ID获取 玩家信息
            var data = JSON.parse(this.io.get("userinfo")) ;
            if(data.token != null){     //获取用户登录信息
                var xhr = cc.beimi.http.httpGet("/api/guest?token="+data.token.id, this.sucess , this.error , this);
            }
        }
    },
    wxLogin:function(msg){
        cc.beimi.logo = msg.headimgurl;
        var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
    },
    newLogin:function(msg){
        var data = {
            "city":"Hangzhou",
            "country":"CN",
            "headimgurl": msg.smallAvatar,
            "nickname": msg.nickName,
            "openid": msg.openId,
            "privilege": [],
            "province":"Zhejiang",
            "sex": msg.gender,
            "unionid": msg.openId
        };
        cc.beimi.logo = msg.smallAvatar;
        var xhr = cc.beimi.http.httpPost("/api/wx/register", data, this.sucess , this.error , this);
    },
    wxchat:function(){
        this.loadding();
        this.loginType = 1;
        if(cc.sys.os == cc.sys.OS_WINDOWS){
            var msg = {
                "city":"Hangzhou",
                "country":"CN",
                "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132",
                "nickname":"善了个哉",
                "openid":"ofBz41d8pV5dHj8P-VdiWLl5BJjk",
                "privilege":[],
                "province":"Zhejiang",
                "sex":"1",
                "unionid":"oYWmV1XTySv8fXugbsgfriv8HcsA"
            };
            cc.beimi.logo = msg.headimgurl;
            var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
        }
        if(cc.sys.os == cc.sys.OS_ANDROID){
            this.loginFlag = true;
            //调用java代码进行微信登录
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "wxLogin","()V");
        }
        else if (cc.sys.os == cc.sys.OS_IOS){ 
            this.loginFlag = true;
            jsb.reflection.callStaticMethod("AppController", "requestLocation");
        }
    },
    test:function(){
        this.loadding();
        this.loginType = 2;
        if(cc.sys.os == cc.sys.OS_WINDOWS){
            var msg = {
                "city":"Hangzhou",
                "country":"CN",
                "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132",
                "nickname":"秦时明月",
                "openid":"1GA9ql0KDHghppc4qgq+UA==",
                "privilege":[],
                "province":"Zhejiang",
                "sex":"1",
                "unionid":"gGA9ql0KDHghppc4qgq+UA=="
            };
            cc.beimi.logo = msg.headimgurl;
            var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
        }
    },
    test2:function(){
        this.loadding();
        this.loginType = 2;
        if(cc.sys.os == cc.sys.OS_WINDOWS){
            var msg = {
                "city":"Hangzhou",
                "country":"CN",
                "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132",
                "nickname":"诸子百家",
                "openid":"2GA9ql0KDHghppc4qgq+UA==",
                "privilege":[],
                "province":"Zhejiang",
                "sex":"1",
                "unionid":"gGA9ql0KDHghppc4qgq+UA=="
            };
            cc.beimi.logo = msg.headimgurl;
            var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
        }
    },
    sgLogin:function(){
        this.loadding();
        this.loginType = 2;
        if(cc.sys.os == cc.sys.OS_WINDOWS){
            var msg = {
                "city":"Hangzhou",
                "country":"CN",
                "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132",
                "nickname":"逸逸逸尘",
                "openid":"gGA9ql0KDHghppc4qgq+UA==",
                "privilege":[],
                "province":"Zhejiang",
                "sex":"1",
                "unionid":"gGA9ql0KDHghppc4qgq+UA=="
            };
            cc.beimi.logo = msg.headimgurl;
            var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
        }
        if(cc.sys.os == cc.sys.OS_ANDROID){
            this.loginFlag = true;
            //调用java代码进行微信登录
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "sgLogin","()V");
        }
    },
    update:function(dt){
        if(this.loginFlag)
        {
            let self = this;
            var wxCode = null;
            var sgCode = null;
            if(cc.sys.os == cc.sys.OS_IOS){
                wxCode = jsb.reflection.callStaticMethod("AppController", "requestLocation");
                //微信登录
                if(this.loginType==1){
                    if(wxCode){
                        this.loginFlag = false;
                        this.closeloadding();
                    }
                }
            }
            else if(cc.sys.os == cc.sys.OS_ANDROID){
                //微信登录
                if(this.loginType==1){
                    wxCode = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getCode", "()Ljava/lang/String;");
                    if(wxCode){
                        this.getAccessToken(wxCode);
                    }
                }
                //闲聊登录
                else if(this.loginType==2){
                    sgCode = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getSgCode", "()Ljava/lang/String;");
                    //this.sanm.string = sgCode;
                    if(sgCode){
                        this.getSgToken(sgCode);
                    }
                }
            }
        }
    },
    //闲聊
    getSgToken:function(code){
        this.loginFlag = false;
        var url = "https://ssgw.updrips.com/oauth2/accessToken";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                var msg = JSON.parse(response).data;
                var access_token = msg.access_token;
                var refresh_token = msg.refresh_token;
                self.getSgUserInfo(access_token);
            }
        };
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        var data="appid="+SG_APPID+"&appsecret="+SG_APPSECRET+"&grant_type=authorization_code&code="+code;
        xhr.open("POST",url,true);
        xhr.send(data);
        //this.sanm.string = code;
    },
    getSgUserInfo:function(access_token){
        var url = "https://ssgw.updrips.com/resource/user/getUserInfo";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                var msg = JSON.parse(response).data;
                self.newLogin(msg)
            }
        };
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        var data="access_token="+access_token;
        xhr.open("POST",url,true);
        xhr.send(data);
        //this.sanm.string = "3";
    },
    //微信
    getAccessToken:function(code){
        this.loginFlag = false;
        //获取accessToken
        var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx194377749f238791&secret=11f3b2bd5c2c852f35bea61df3e6136e&code=" + code + "&grant_type=authorization_code";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                var msg = JSON.parse(response);
                var access_token = msg.access_token;
                var refresh_token = msg.refresh_token;
                var openid = msg.openid;
                //如果超时进行重新刷新accessToken
                if(msg.expires_in >= 7200){
                    //刷新accesstoken
                    self.freshAccessToken(refresh_token).then(function(data){
                       access_token = data;
                       self.getUserInfo(access_token,openid);
                       //cc.director.loadScene("hall");
                    });
                }else{
                    self.getUserInfo(access_token,openid);
                    //this.sanm.string = "openid:"+openid;
                    //cc.director.loadScene("hall");
                }
            }
        };
        xhr.open("GET",url,true);
        xhr.send();
    },
    getUserInfo:function(access_token,openid){       
        //获取用户信息
        var url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token + "&openid="+openid;
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                var msg = JSON.parse(response);
                //self.sanm.string = msg.nickname;
                // console.log("msg is " , msg);
                // console.log("nickName is " + msg.nickname);
                // console.log("city is " + msg.city);
                // console.log("country " + msg.country);
                // console.log("sex is  " + msg.sex);
                //var xhr = cc.beimi.http.httpPost("/api/wx/register", msg, this.sucess , this.error , this);
                self.wxLogin(msg)
            }
        };
        xhr.open("GET",url,true);
        xhr.send();
    },
    freshAccessToken:function(refresh_token){
        var url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wx194377749f238791&grant_type=refresh_token&refresh_token="+refresh_token;
        var self = this;
        var xhr = new XMLHttpRequest();
        var ac;
        return new Promise(function(resolve,reject){
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    var response = xhr.responseText;
                    var msg = JSON.parse(response);
                    ac = msg.access_token;
                    resolve(ac);
                }
            };
            xhr.open("GET",url,true);
            xhr.send();
        });
        
    },
    sucess:function(result , object){
        //this.sanm.string = "7";
        console.log(result)
        var data = JSON.parse(result) ;
        //测试模式写死
        //data.gametype = "hall";
        if(data!=null && data.token!=null && data.data!=null){
            //放在全局变量
            object.reset(data , result);
            //修改全局游戏状态
            cc.beimi.gamestatus = data.data.gamestatus ;
            /**
             * 登录成功后即创建Socket链接
             */
            object.connect();
            //预加载场景
            if(cc.beimi.gametype!=null && cc.beimi.gametype != ""){//只定义了单一游戏类型 ，否则 进入游戏大厅
                console.log('gameType:'+cc.beimi.gametype);
                object.scene(cc.beimi.gametype , object) ;
            }else{
                
            }
        }
    },
    error:function(object){
        object.closeloadding(object.loaddingDialog);
        object.alert("网络异常，服务访问失败");
    }
});
